<template>
    <div class="main-content">
        <el-tabs>
            <el-tab-pane label="智能巡更">
                <div class="intelligent-patrol" v-loading="isLoading">
                    <div class="intelligent-patrol-search">
                        <div></div>
                        <el-button @click="addPatrol" icon="el-icon-plus" v-if="is_superuser || permission_map['23a']" type="primary">新增</el-button>
                    </div>
                    <div class="patrol-project">
                        <div class="project-ul" v-if="patrolList && patrolList.length > 0">
                            <div class="project-item" v-for="(item, $index) in patrolList" :key="this">
                                <div class="project-item-con" @click="patrolItemBtn(item)">
                                    <img v-if="item.img" class="project-img" :src="$IMGURL+item.img"/>
                                    <img v-else class="project-img" src="../../../assets/default_img.png"/>
                                    <div class="project-item-content">
                                        <span class="porject-item-info">
                                            <div><span class="info-label">巡更区域：</span><span class="info-text">{{item.name}}</span></div>
                                            <div>
                                                <span class="info-label">巡更点：</span
                                                ><span class="patrol-time">{{item.point_list?item.point_list.join('、'):''}}</span>
                                            </div>
                                        </span>
                                    </div>
                                    <div class="porject-item-edit-del">
                                        <i @click.stop="editPatrol(item)" v-if="is_superuser || permission_map['23a']" class="el-icon-edit-outline"></i>
                                        <i @click.stop="delPatrol(item.id, $index)" v-if="is_superuser || permission_map['23a']" class="el-icon-delete"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="project-epmty-main" v-if="patrolList && patrolList.length <= 0">
                            <img src="../../../assets/model_icon.png"/>
                            <div class="create-area-tip">暂无巡更区域信息</div>
                            <div @click="addPatrol" v-if="is_superuser || permission_map['23a']" class="create-area-text">创建区域</div>
                        </div>
                    </div>
                    <el-dialog :title="isEdit?'修改巡更':'新增巡更'" :visible.sync="dialogArea" width="730px" v-loading="formIsLoading">
                        <el-form ref="patrolForm" :rules="rules" class="patrol-form" :model="patrolForm" label-width="110px" id="patrolForm">
                            <el-form-item label="巡更区域：" prop="address">
                                <el-input v-model="patrolForm.address" placeholder="请输入巡更区域"></el-input>
                            </el-form-item>
                            <el-form-item label="巡更点：" prop="projects">
                                <div class="form-divs">
                                    <div class="form-div" v-for="(item, index) in patrolForm.projects" :key="index">
                                        <el-input v-model="patrolForm.projects[index]" placeholder="请输入巡更点"></el-input>
                                        <i v-if="patrolForm.projects.length === index+1" class="project-icon el-icon-circle-plus-outline" @click.prevent="addPatrolProject"></i
                                        ><i v-if="index!==0" class="project-icon el-icon-delete" @click.prevent="removeProject(index)"></i>
                                    </div>
                                </div>
                            </el-form-item>
                            <el-form-item label="区域图片：" prop="areaImg"">
                                <el-upload
                                    class="avatar-uploader"
                                    action="#"
                                    :show-file-list="false"
                                    :on-change="changeFile"
                                    :before-upload="beforeAvatarUpload"
                                    accept="image/png, image/jpg, image/jpeg">
                                        <img v-if="patrolForm.areaImg" :src="patrolForm.areaImg" class="avatar" />
                                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                                </el-upload>
                            </el-form-item>
                        </el-form>
                        <span slot="footer" class="dialog-footer">
                            <el-button @click="dialogArea = false">取消</el-button>
                            <el-button type="primary" @click="patrolSubmit">确定</el-button>
                        </span>
                    </el-dialog>
                </div>
            </el-tab-pane>
        </el-tabs>
    </div>
</template>
<script>
    import empty from '../../../components/empty.vue';
    export default {
        components: {
            'v-empty': empty
        },
        data() {
            return {
                date: '',
                isLoading: false,
                isEdit: false,
                dialogArea: false,
                staffList: [],
                patrolList: null,
                patrolForm: {
                    address: '',
                    projects: [''],
                    areaImgRaw: '',
                    areaImg: ''
                },
                rules: {
                    address: [
                        { required: true, message: '请输入巡更区域', trigger: 'blur' }
                    ],
                    projects: [
                        { required: true, message: '请输入巡更点', trigger: 'blur' }
                    ]
                },
                formIsLoading: false,
                fielId: '',
                permission_map: {},
                is_superuser: false
            }
        },
        watch: {
            'date': function() {
                this.$store.commit('patrolDate', this.date);
            }
        },
        created() {
            if(localStorage.getItem('user_info')) {
                this.permission_map = JSON.parse(localStorage.getItem('user_info')).permission_map;
                this.is_superuser = JSON.parse(localStorage.getItem('user_info')).is_superuser;
            }
            if(this.$store.state.patrolDate) {
                this.date = this.$store.state.patrolDate;
            }else {
                this.date = this.common.YMD(Date.parse(new Date())/1000);
            }
            this.requestInfo();
        },
        methods: {
            requestInfo() {
                this.isLoading = true;
                this.$http.get(`/api/v1/patrol/field/`)
                .then((res) => {
                    this.isLoading = false;
                    this.patrolList = res.data;
                    this.patrolList.forEach((v) => {
                        let func = new Function('return (' + v.point_list + ');');
                        v.point_list = func();
                    })
                })
                .catch(() => {
                    this.isLoading = false;
                })
            },
            changeFile(res) {
                let _that = this;
                var reader = new FileReader();
                reader.readAsDataURL(res.raw);
                reader.onloadend = function(e) {
                    _that.$set(_that.patrolForm, 'areaImg', e.target.result);
                    _that.patrolForm.areaImgRaw = res.raw;
                };
            },
            beforeAvatarUpload(file) {
                const isLt2M = file.size / 1024 / 1024 < 10;
                if (!isLt2M) {
                    this.$message.error("上传头像图片大小不能超过 10MB!");
                }
                return false;
            },
            patrolItemBtn(item) {
                this.$router.push({path: `/Security/PatrolDetailManage?id=${item.id}&name=${item.name}`});
            },
            // 添加巡更点
            addPatrol() {
                this.dialogArea = true;
                this.isEdit = false;
                this.$nextTick(() => {
                    var container = this.$el.querySelector("#patrolForm");
                    container.scrollTop = 0;
                    this.patrolForm = {
                        address: '',
                        projects: [''],
                        areaImgRaw: '',
                        areaImg: ''
                    }
                    this.$refs.patrolForm.clearValidate();
                });
            },
            // 修改巡更点
            editPatrol(item) {
                this.dialogArea = true;
                this.isEdit = true;
                this.fielId = item.id;
                this.patrolForm = {
                    address: item.name,
                    projects: item.point_list,
                    areaImgRaw: item.img,
                    areaImg: item.img ? this.$IMGURL + item.img:item.img
                }
                this.$nextTick(() => {
                    var container = this.$el.querySelector("#patrolForm");
                    container.scrollTop = 0;
                    this.$refs.patrolForm.clearValidate();
                })
            },
            // 删除巡更点
            delPatrol(id, index) {
                this.$confirm('您是否确定删除此巡更点，删除后将同时删除此巡更点下的所有巡更记录。', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.isLoading = true;
                    this.$http.delete(`/api/v1/patrol/field/${id}`)
                    .then((res) => {
                        this.isLoading = false;
                        this.patrolList.splice(index, 1);
                        this.$message.success('删除成功');
                    })
                    .catch(()=>{
                        this.isLoading = false;
                    })
                }).catch(() => {});
            },
            // 添加巡更项目
            addPatrolProject() {
                this.patrolForm.projects.push('');
            },
            // 
            removeProject(index) {
                this.patrolForm.projects.splice(index, 1);
            },
            // 添加巡更时间
            addPatrolTimes() {
                if(this.patrolForm.times.length >= 3) this.$message.warning('最多只能添加三个巡更时间');
                else this.patrolForm.times.push({
                    startTime: '',
                    endTime: ''
                });
            },
            removeTimes(index) {
                this.patrolForm.times.splice(index, 1);
            },
            // 新增巡更项目提交
            patrolSubmit() {
                let times = [];
                this.$refs['patrolForm'].validate((valid) => {
                    if (valid) {
                        let projects = this.patrolForm.projects.some((val)=>{
                            return !val;
                        })
                        if(projects) this.$message.warning('请输入巡更点');
                        this.formIsLoading = true;
                        let params = new FormData();
                        params.append('name', this.patrolForm.address);
                        params.append('point_list', this.patrolForm.projects.join(','));
                        if(this.patrolForm.areaImgRaw!=null && typeof  this.patrolForm.areaImgRaw =='object') params.append('img', this.patrolForm.areaImgRaw);
                        if(this.isEdit) {
                            this.$http.put(`/api/v1/patrol/field/${this.fielId}`, params)
                            .then((res) => {
                                this.dialogArea = false;
                                this.formIsLoading = false;
                                this.$message.success('巡更点修改成功！');
                                this.requestInfo();
                            })
                            .catch(() => {
                                this.formIsLoading = false;
                            })
                        }else {
                            this.$http.post('/api/v1/patrol/field/', params)
                            .then((res) => {
                                this.dialogArea = false;
                                this.formIsLoading = false;
                                this.$message.success('巡更点添加成功！');
                                this.requestInfo();
                            })
                            .catch(() => {
                                this.formIsLoading = false;
                            })
                        }
                    }
                })
            }
        }
    }
</script>
<style lang="scss" scoped>
    .intelligent-patrol {
        width: 100%;
        height: 100%;
        .intelligent-patrol-search {
            width: 100%;
            display: flex;
            justify-content: space-between;
        }
        .patrol-project {
            width: 100%;
            .patrol-project-title {
                width: 100%;
                font-weight: bold;
                font-size: 18px;
                display: flex;
                align-items: center;
                padding: 0 10px;
                box-sizing: border-box;
                .patrol-project-title-icon {
                    width: 16px;
                    height: 16px;
                    border-radius: 50%;
                    background: green;
                    margin-right: 10px;
                }
                .title-icon-unfinished {
                    background: red;
                }
            }
            .project-ul {
                width: 100%;
                display: flex;
                flex-wrap: wrap;
                .project-item {
                    width: 25%;
                    padding: 0 10px;
                    box-sizing: border-box;
                    margin-top: 20px;
                    .project-item-con {
                        width: 100%;
                        border: 1px solid #e5e5e5;
                        border-radius: 5px;
                        overflow: hidden;
                        cursor: pointer;
                        position: relative;
                        .project-img {
                            width: 100%;
                            height: 160px;
                            object-fit: contain;
                        }
                        .project-item-content {
                            width: 100%;
                            padding: 12px;
                            box-sizing: border-box;
                            border-top: 1px solid #e5e5e5;
                            display: flex;
                            flex-direction: row;
                            justify-content: space-between;
                            min-height: 100px;
                            .porject-item-info {
                                &>div {
                                    margin-top: 10px;
                                    display: flex;
                                    .info-label {
                                        width: 80px;
                                        display: inline-block;
                                        text-align: right;
                                        color: #999;
                                    }
                                    .info-text {
                                        width: calc(100% - 80px);
                                        overflow : hidden;
                                        text-overflow: ellipsis;
                                        display: -webkit-box;
                                        -webkit-line-clamp: 1;
                                        -webkit-box-orient: vertical;
                                    }
                                    .patrol-time {
                                        /* flex: 1; */
                                        width: calc(100% - 80px);
                                        overflow : hidden;
                                        text-overflow: ellipsis;
                                        display: -webkit-box;
                                        -webkit-line-clamp: 2;
                                        -webkit-box-orient: vertical;
                                        &>div {
                                            margin-top: 10px;
                                        }
                                        &>div:first-child {
                                            margin-top: 0;
                                        }
                                    }
                                }
                                &>div:first-child {
                                    margin-top: 0;
                                }
                            }
                            .project-item-status-img {
                                display: flex;
                                align-items: flex-end;
                                flex-direction: column;
                                justify-content: space-between;
                                .project-status-green, .project-status-red {
                                    background: red;
                                    color: #fff;
                                    padding: 4px 12px;
                                    font-size: 12px;
                                    border-radius: 4px;
                                    background: green;
                                }
                                .project-status-red {
                                    background: red;
                                }
                                .project-er {
                                    width: 200px;
                                    height: 200px;
                                }
                                .project-er-icon {
                                    width: 40px;
                                    height: 40px;
                                }
                            }
                        }
                        .porject-item-edit-del {
                            position: absolute;
                            right: 0;
                            top: 0;
                            background: rgba(0, 0, 0, 0.5);
                            padding: 0 6px;
                            &>i {
                                color: #fff;
                                padding: 8px 6px;
                                font-size: 18px;
                            }
                        }
                    }
                    .project-item-con:hover {
                        box-shadow: 0 0 10px rgba(0,0,0,.2);
                    }
                }
            }
            .project-epmty-main {
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                margin: 200px 0;
                &>img {
                    width: 80px;
                    height: 80px;
                }
                .create-area-tip {
                    margin: 12px 0;
                }
                .create-area-text {
                    font-weight: bold;
                    font-size: 18px;
                    cursor: pointer;
                    color: #409eff;
                }
            }
        }
        .patrol-form {
            width: 100%;
            max-height: 500px;
            overflow: auto;
            .project-icon, .project-icon-n {
                font-size: 22px;
                margin-left: 12px;
                cursor: pointer;
            }
            .project-icon-n {
                margin-top: 9px;
            }
            ::v-deep .el-input {
                width: 280px;
            }
            .form-divs {
                .form-div {
                    display: flex;
                    align-items: center;
                    margin-top: 12px;
                    ::v-deep .el-input {
                        width: 200px;
                    }
                    .form-div-line {
                        margin: 0 10px;
                    }
                }
                &>div:first-child {
                    margin-top: 0;
                }
            }
            .form-tips {
                font-size: 12px;
                color: #88B;
                margin-top: 10px;
            }
            .avatar-uploader-icon {
                font-size: 28px;
                color: #8c939d;
                width: 148px;
                height: 148px;
                line-height: 148px;
                text-align: center;
                border: 1px solid #e5e5e5;
            }
            .avatar {
                width: 148px;
                height: 148px;
                display: block;
                object-fit: contain;
                border: 1px solid #e5e5e5;
            }
        }
    }
</style>